import { DatePipe } from '@angular/common';
import { BaseService } from '@service/base.service';
import { AbsFormUtil } from '@abstract/form';
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { GenderList } from '@app/store/dict';
import { IGridRegisters } from '@model/grid';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { TreeService } from '@service/tree.service';
import { GridService } from '@service/grid.service';
import { deepClone } from '@utils/lang';
import { getUuid } from '@utils/web';
const ID = '123456789123456789';
@Component({
	selector: 'app-grid-household-edit',
	templateUrl: './grid-household-edit.component.html',
	styleUrls: ['./grid-household-edit.component.less'],
	providers: [DatePipe]
})
export class GridHouseholdEditComponent extends AbsFormUtil implements OnInit {
	@Input() id: number;
	genderList = GenderList;
	areaOptions = [];
	areaList = [];
	tagList = [];
	lists = [];

	registers = [];
	tenements = [];

	editData: IGridRegisters = null;
	constructor(
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private nzModalRef: NzModalRef,
		private baseService: BaseService,
		private treeService: TreeService,
		private gridService: GridService,
		private datePipe: DatePipe
	) {
		super();
	}

	ngOnInit() {
		this.buildForm();
		this.getTags();
		this.getAreaOption();
		this.getFormControl('rental').valueChanges.subscribe(val => {
			const arr = this.lists;
			this.editData = null;
			if (val) {
				this.lists = this.tenements;
				this.lists = [...this.lists];
				this.registers = arr;
				return;
			}
			this.lists = this.registers;
			this.lists = [...this.lists];
			this.tenements = arr;
		});
	}
	private async getHouseholdInfo() {
		const result = await this.gridService.getHouseholdInfo(this.id);
		const householdInfo = result.data;
		const areaItem = this.areaList.find(itm => itm.id === String(householdInfo.areaId));
		householdInfo.areaId = areaItem ? this.getAreaId(areaItem, [String(areaItem.id)]) : '';
		householdInfo.tags = householdInfo?.tags ? householdInfo.tags.split(',') : [];
		householdInfo.rental = householdInfo.rental * 1;
		householdInfo.rental === 0 ? this.registers = householdInfo?.registers?.map(it => {it.delFlag = '0'; return it}) || []  : this.tenements = householdInfo?.tenements?.map(it => {it.delFlag = '0'; return it}) || []; 
		// this.lists = householdInfo.rental === 0 ? this.tenements : this.registers;
		console.log(this.registers);
		this.validateForm.patchValue(householdInfo);
	}
	getAreaId(area, result: string[]) {
		const areaItem = this.areaList.find(itm => itm.id === String(area.parentId));
		if (areaItem) {
			result.unshift(String(areaItem.id));
			if (areaItem.parentId) {
				return this.getAreaId(areaItem, result);
			}
			return result;
		}
	}

	private async getAreaOption() {
		const result = await this.baseService.getAddrList({parentId:0, areaLevel: 0});
		this.areaList = result.data;
		this.areaList.forEach(it => {
			it.label = it.areaFullName;
			it.value = it.id;
			it.isLeaf = !this.areaList.some(itm => itm.parentId == it.id);
		});
		if (this.id) {
			this.getHouseholdInfo();
		}
		this.areaOptions = this.treeService.convertListToTree(this.areaList, 0);
	}
	buildForm() {
		this.validateForm = this.fb.group({
			contact: [''],
			contractNumber: [''],
			householdCode: [''],
			address: ['', Validators.required],
			rental: [0],
			areaId: [''],
			housemaster: ['', Validators.required],
			housemasterContactNum: ['', Validators.required],
			tags: [[]],
		});
	}

	private async getTags() {
		const result = await this.baseService.getHouseholdTagList();
		this.tagList = result.data;
	}

	onSubmit() {
		this.markAsDirty();
		if (this.validateForm.invalid) {
			return;
		}
		const formRes = this.validateForm.value;
		const lists = deepClone(this.lists);
		lists.forEach(list => {
			list.birthdate = list.birthdate ? this.datePipe.transform(list.birthdate, 'yyyy-MM-dd') : '';
			list.id = list.id.length > 10 ? '' :  list.id;
		});
		return {...formRes, lists};
	}
	destroyModal() {
		this.nzModalRef.destroy();
	}



	del(item: IGridRegisters) {
		if (item.id.length > 10) {
			const idx = this.lists.findIndex(it => it.id === item.id);
			this.lists.splice(idx, 1);
			this.lists = [...this.lists];
			return;
		}
		item.delFlag = '1';
	}
	add() {
		if (this.editData?.id) {
			this.nzMessageService.info('一次只能编辑一条数据!');
			return;
		}
		const registers = new IGridRegisters()
		registers.id = ID;
		registers.delFlag = '0';
		this.lists.unshift(registers);
		this.lists = [...this.lists];
		this.editData = registers;
	}
	edit(item: IGridRegisters) {
		if (this.editData) {
			this.nzMessageService.info('一次只能编辑一条数据!');
			return;
		}
		this.editData = deepClone(item);
	}
	cancel() {
		if (this.editData.id === ID) {
			this.lists.shift();
			this.lists = [...this.lists];
		}
		this.editData = null;
	}
	save(item: IGridRegisters) {
		const editData = this.editData;
		editData.householdId = this.id;
		editData.id = editData.id === ID ? getUuid() : editData.id;
		Object.assign(item, editData);
		this.editData = null;
		this.getFormControl('rental').value  ? this.tenements = this.lists || []  : this.registers = this.lists || []; 

	}
}
